package com.jpcc.vw.onlineRadio.activity;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Popup;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.RemoteException;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.bumptech.glide.Glide;
import com.cns.android.atmospherelamp.AtmosphereLampManager;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.jpcc.vw.onlineRadio.R;
import com.jpcc.vw.onlineRadio.adapter.AlbumDetailDownloadAdapter;
import com.jpcc.vw.onlineRadio.application.MusicApplication;
import com.jpcc.vw.onlineRadio.base.BaseActivity;
import com.jpcc.vw.onlineRadio.constants.Constants;
import com.jpcc.vw.onlineRadio.db.DatabaseHelperOrm;
import com.jpcc.vw.onlineRadio.db.DownloadTrackDbBean;
import com.jpcc.vw.onlineRadio.model.action.DeleteDownloadAlbumAction;
import com.jpcc.vw.onlineRadio.model.action.WaveAction;
import com.jpcc.vw.onlineRadio.model.bean.Announcer;
import com.jpcc.vw.onlineRadio.model.bean.SubordinatedAlbum;
import com.jpcc.vw.onlineRadio.model.bean.Track;
import com.jpcc.vw.onlineRadio.service.AlbumRadioAudioPlayer;
import com.jpcc.vw.onlineRadio.utils.ToastUtils;
import com.jpcc.vw.onlineRadio.utils.TrackUtils;
import com.lzy.okhttpserver.download.DownloadManager;
import com.orhanobut.logger.Logger;

import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import de.hdodenhof.circleimageview.CircleImageView;

public class DownloadAlbumDetailActivity extends BaseActivity {

    private long albumId;
    private DatabaseHelperOrm helper;
    private List<DownloadTrackDbBean> sources;
    @BindView(R.id.recyclerview_tracks)
    ListView recyclerview_tracks;
    @BindView(R.id.imv_album_cover)
    CircleImageView imv_album_cover;
    @BindView(R.id.tv_album_host)
    TextView tv_album_host;
    @BindView(R.id.layout_back)
    RelativeLayout layout_back;
    @BindView(R.id.imv_top_search)
    ImageView imv_top_search;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.imv_top_bottom_line)
    ImageView imv_top_bottom_line;
    @BindView(R.id.imv_back_main)
    ImageView imv_back_main;
    @BindView(R.id.imv_new_search)
    ImageView imv_new_search;
    private AlbumDetailDownloadAdapter adapter;
    private BroadcastReceiver receiver;

    @Override
    public int getLayoutId() {
        return R.layout.activity_album_detail_download;
    }

    @Override
    public void setupView() {
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);
        helper = DatabaseHelperOrm.getHelper(this);
        albumId = getIntent().getLongExtra("key_album_id", -1);
        if (albumId == -1) {
            this.finish();
        }
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent != null) {
                    if ("com.jpcc.vw.DownloadAlbumDetailActivity".equals(intent.getAction())) {
                        Bundle bundle = intent.getExtras();
                        if (bundle != null) {
                            String action = bundle.getString("action");
                            if ("DeleteDownload".equals(action)) {
                                DeleteDownloadAlbumAction event = new DeleteDownloadAlbumAction();
                                event.setAlbumId(bundle.getLong("AlbumId"));
                                event.setTrackId(bundle.getLong("TrackId"));
                                delete(event);
                            }
                        }
                    }
                }
            }
        };
        IntentFilter deleteFilter = new IntentFilter("com.jpcc.vw.DownloadAlbumDetailActivity");
        this.registerReceiver(receiver, deleteFilter);
        layout_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DownloadAlbumDetailActivity.this.finish();
            }
        });
        imv_new_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(DownloadAlbumDetailActivity.this, SearchActivity.class);
                startActivity(intent);
            }
        });
        sources = new ArrayList<>();
        adapter = new AlbumDetailDownloadAdapter(sources, this);
        recyclerview_tracks.setAdapter(adapter);
        prepareDownloadData();
        recyclerview_tracks.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                List<Track> infos = new ArrayList<>();
                for (DownloadTrackDbBean db : sources) {
                    Track track = new Track();
                    SubordinatedAlbum subordinatedAlbum = new SubordinatedAlbum();
                    subordinatedAlbum.setId(db.getAlbumId());
                    subordinatedAlbum.setAlbumTitle(db.getAlbumName());
                    Announcer announcer = new Announcer();
                    announcer.setNickname(db.getAuthor());
                    track.setId(db.getTrackId());
                    track.setTrackTitle(db.getTrackName());
                    track.setCoverUrlLarge(db.getCover());
                    track.setPlayUrl32(db.getTrackUrl());
                    track.setCanDownload(false);
                    track.setDownloadUrl("");
                    track.type = "album";
                    track.setDuration(db.getDuration() / 1000);
                    track.setAnnouncer(announcer);
                    track.setSubordinatedAlbum(subordinatedAlbum);
                    infos.add(track);
                }
                Constants.LastModeFlag = false;
                AlbumRadioAudioPlayer.get().setOnSources(infos, position, 1, -1);
                adapter.notifyDataSetChanged();
            }
        });
    }


    @Override
    public void setupData() {
        if (Constants.isRelease) {
            try {
                boolean atmosphereStatus = AtmosphereLampManager.getInstance(this).isHmiAtmosphereLampOn();
                String color = AtmosphereLampManager.getInstance(this).getHmiAtmosphereLampColor();
                doAtmosphere(atmosphereStatus, color);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public void doAtmosphere(boolean rgbOn, String color) {
        Logger.i("doAtmosphere" + "rgbOn-->" + rgbOn);
        Logger.i("doAtmosphere" + "color-->" + color);
        if (rgbOn) {
            if (TextUtils.isEmpty(color)) {
                imv_top_bottom_line.setColorFilter(Color.TRANSPARENT);
            } else {
                imv_top_bottom_line.setColorFilter(Color.parseColor(color));
            }
        } else {
            imv_top_bottom_line.setColorFilter(Color.TRANSPARENT);
        }
    }

    private void delete(DeleteDownloadAlbumAction action){
        DeleteBuilder deleteBuilder = null;
        try {
            DownloadManager downloadManager = DownloadManager.getInstance(DownloadAlbumDetailActivity.this);
            if (downloadManager != null) {
                downloadManager.removeTaskByTrackId(action.getTrackId() + "");
            }
            deleteBuilder = helper.getDownloadDao().deleteBuilder();
            deleteBuilder.where().eq("albumId", action.getAlbumId()).and().eq("trackId", action.getTrackId());
            deleteBuilder.delete();
            File file = new File(TrackUtils.getTrackDir());
            for (File subFile : file.listFiles()) {
                if (subFile.getName().contains("" + action.getAlbumId() + action.getTrackId())) {
                    boolean deleteFlag = subFile.delete();
                    if (deleteFlag) {
                        ToastUtils.show(getResources().getString(R.string.string_93));
                    } else {
                        ToastUtils.show(getResources().getString(R.string.string_94));
                    }
                }
            }
            prepareDownloadData();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void onEvent(DeleteDownloadAlbumAction action) {
        if (action.getAlbumId() != 0 && action.getTrackId() != 0) {

            if (!Constants.isRelease) {
                MaterialDialog dialog = new MaterialDialog.Builder(this).title(getResources().getString(R.string.string_30)).content(getResources().getString(R.string.string_116)).positiveText(getResources().getString(R.string.string_32)).negativeText(getResources().getString(R.string.string_33)).onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        DeleteBuilder deleteBuilder = null;
                        try {
                            DownloadManager downloadManager = DownloadManager.getInstance(DownloadAlbumDetailActivity.this);
                            if (downloadManager != null) {
                                downloadManager.removeTaskByTrackId(action.getTrackId() + "");
                            }
                            deleteBuilder = helper.getDownloadDao().deleteBuilder();
                            deleteBuilder.where().eq("albumId", action.getAlbumId()).and().eq("trackId", action.getTrackId());
                            deleteBuilder.delete();
                            File file = new File(TrackUtils.getTrackDir());
                            for (File subFile : file.listFiles()) {
                                if (subFile.getName().contains("" + action.getAlbumId() + action.getTrackId())) {
                                    boolean deleteFlag = subFile.delete();
                                    if (deleteFlag) {
                                        ToastUtils.show(getResources().getString(R.string.string_93));
                                    } else {
                                        ToastUtils.show(getResources().getString(R.string.string_94));
                                    }
                                }
                            }
                            prepareDownloadData();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                    }
                }).build();
                dialog.show();
            } else {
//                NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//                Intent setAlertIntent = new Intent("com.jpcc.vw.DownloadAlbumDetailActivity");
//                setAlertIntent.putExtra("action", "DeleteDownload");
//                setAlertIntent.putExtra("AlbumId", action.getAlbumId());
//                setAlertIntent.putExtra("TrackId", action.getTrackId());
//                PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, setAlertIntent, PendingIntent.FLAG_UPDATE_CURRENT);
//                Popup popup = new Popup(getResources().getString(R.string.string_30), getResources().getString(R.string.string_116));
//                popup.setActionOne(getResources().getString(R.string.string_32), pendingIntent);
//                popup.setActionCancel(getResources().getString(R.string.string_33), "cancel");
//                notificationManager.addPopup(0x0006, popup);



                DeleteBuilder deleteBuilder = null;
                try {
                    DownloadManager downloadManager = DownloadManager.getInstance(DownloadAlbumDetailActivity.this);
                    if (downloadManager != null) {
                        downloadManager.removeTaskByTrackId(action.getTrackId() + "");
                    }
                    deleteBuilder = helper.getDownloadDao().deleteBuilder();
                    deleteBuilder.where().eq("albumId", action.getAlbumId()).and().eq("trackId", action.getTrackId());
                    deleteBuilder.delete();
                    File file = new File(TrackUtils.getTrackDir());
                    for (File subFile : file.listFiles()) {
                        if (subFile.getName().contains("" + action.getAlbumId() + action.getTrackId())) {
                            boolean deleteFlag = subFile.delete();
                            if (deleteFlag) {
                                ToastUtils.show(getResources().getString(R.string.string_93));
                            } else {
                                ToastUtils.show(getResources().getString(R.string.string_94));
                            }
                        }
                    }
                    prepareDownloadData();
                } catch (SQLException e) {
                    e.printStackTrace();
                }

            }
        }
    }


    private void prepareDownloadData() {
        List<DownloadTrackDbBean> datas = new ArrayList<>();
        try {
            datas.addAll(helper.getDownloadDao().queryBuilder().orderBy("timeStamp", false).where().eq("albumId", albumId).and().eq("userId", MusicApplication.GetUserId()).query());
//            datas = helper.getDownloadDao().queryBuilder().where().eq("albumId", albumId).and().eq("userId", MusicApplication.GetUserId()).query();
            sources.clear();
            sources.addAll(datas);
            adapter.setDatas(sources);
            if (sources.size() > 0) {
                tv_title.setText(sources.get(0).getAlbumName());
                Glide.with(this).load(sources.get(0).getCover()).into(imv_album_cover);
                tv_album_host.setText(sources.get(0).getAuthor());
            }
            else{
                DownloadAlbumDetailActivity.this.finish();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    @Override
    protected void onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        this.unregisterReceiver(receiver);
        super.onDestroy();
    }

    public void onEvent(WaveAction action) {
        adapter.notifyDataSetChanged();
    }
}
